<template>
  <div class="body">
    <div class="table_filtrate">
      <div class="tf_item">
        <div class="tag">职位</div>
        <el-select
          class="input"
          size="mini"
          clearable
          v-model="tableParams.group_id"
          :filterable="true"
          placeholder="请选择"
        >
          <el-option
            v-for="g in group"
            :key="g.id"
            :label="g.name"
            :value="g.id"
            v-if="![6].includes(g.id)"
          ></el-option>
        </el-select>
      </div>

      <div class="tf_item">
        <div class="tag">搜索</div>
        <el-input
          class="input_fuzzy_search input"
          :filterable="true"
          placeholder="用户名/姓名"
          v-model="tableParams.fuzzy_search"
          size="mini"
          clearable
        >
        </el-input>
      </div>

      <div class="tf_item">
        <div class="tag">状态</div>
        <el-select
          class="input"
          v-model="tableParams.status"
          :filterable="true"
          placeholder="请选择"
          size="mini"
        >
          <el-option label="正常" value="normal"></el-option>
          <el-option label="废弃" value="hidden"></el-option>
        </el-select>
      </div>

      <div class="tf_item">
        <el-button @click="req_list" plain size="mini" type="primary">
          搜索</el-button
        >
      </div>
    </div>

    <div class="table_operate">
      <el-button
        class="btn_add"
        type="primary"
        size="mini"
        @click="handleDialogVisible(true)"
        >添加</el-button
      >
    </div>

    <div class="table-card">
      <el-table
        class="table"
        v-loading="loading.table"
        :data="tableData.data"
        :border="true"
        size="mini"
      >
        <el-table-column sortable prop="id" label="ID" width="80">
        </el-table-column>
        <el-table-column sortable prop="group_name" label="职位" width="90">
        </el-table-column>
        <el-table-column sortable prop="nickname" label="名字"> </el-table-column>
        <el-table-column sortable prop="mobile" label="手机号"> </el-table-column>
        <el-table-column sortable prop="username" label="账号"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-link
              v-if="scope.row.status == 'normal'"
              class="handle"
              type="primary"
              @click="handleTableEdit(scope.$index, scope.row)"
              >编辑</el-link
            >
            <el-link
              v-if="scope.row.status == 'normal'"
              class="handle"
              type="danger"
              @click="handleTableDelete(scope.$index, scope.row)"
              >删除</el-link
            >

            <el-link
              v-if="scope.row.status == 'hidden'"
              class="handle"
              type="warning"
              @click="handleTableRegain(scope.$index, scope.row)"
              >恢复</el-link
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="table-pagination-card"
        @size-change="handleTableSizeChange"
        @current-change="handleTableCurrentChange"
        :current-page="currentPage4"
        :page-sizes="$pageSize"
        :page-size="tableParams.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.total"
      >
      </el-pagination>
    </div>

    <el-dialog
      :title="dialogConfig.title"
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      width="80%"
    >
      <el-form
        :model="form"
        style="width: 380px"
        ref="refForm"
        v-loading="loading.dialog_create"
      >
        <el-form-item
          label="名字"
          prop="nickname"
          :label-width="fromViewCofing.label_width"
          :rules="[{ required: true, message: '名字不能为空' }]"
        >
          <el-input v-model="form.nickname"></el-input>
        </el-form-item>
        <el-form-item
          label="账号"
          prop="account"
          :label-width="fromViewCofing.label_width"
          :rules="[{ required: true, message: '账号不能为空' }]"
        >
          <el-input v-model="form.account" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          :label-width="fromViewCofing.label_width"
        >
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="密码确认"
          prop="password_confirmation"
          :label-width="fromViewCofing.label_width"
        >
          <el-input
            v-model="form.password_confirmation"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
          :label-width="fromViewCofing.label_width"
          :rules="[{ required: true, message: '手机号不能为空' }]"
        >
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="职位"
          prop="group_id"
          :label-width="fromViewCofing.label_width"
          :rules="[{ required: true, message: '手机号不能为空' }]"
        >
          <el-select v-model="form.group_id" placeholder="请选择职位">
            <el-option
              v-for="g in group"
              :label="g.name"
              :key="g.id"
              :value="g.id"
              v-if="![4, 6].includes(g.id)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="from_submit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  apiAgentDelete,
  apiAgentList,
  apiGroupList,
  apiAgentCreate,
  apiAgentUpdate,
  apiAgentUpdateSingle,
} from "@/api/apiCommon";
import { getStorageSync, setStorageSync } from "@/utils/storageUtils.js";
export default {
  name: "Index",
  data() {
    return {
      tableParams: {
        page: 1,
        size: 15,
        status: "normal",
        fuzzy_search: "",
        group_id: 0,
      },
      tableData: {},
      dialogFormVisible: false,
      init_form: {
        id: 0,
        account: "",
        password: "",
        password_confirmation: "",
        mobile: "",
        nickname: "",
        group_id: "",
        status: "normal",
      },
      form: {},
      currentPage4: 1,
      fromViewCofing: {
        input_width: "120px",
        label_width: "120px",
      },
      dialogConfig: {
        title: "添加人员",
      },
      group: [],
      loading: {
        dialog_create: false,
        table: false,
      },
    };
  },
  created() {
    this.from_init();
    this.req_list();
    this.req_group();
  },
  methods: {
    // 列表请求
    req_list() {
      const _this = this;
      this.loading_start("table");
      if (_this.tableParams.fuzzy_search == "") {
        delete _this.tableParams.fuzzy_search;
      }
      if (_this.tableParams.group_id == 0) {
        delete _this.tableParams.group_id;
      }

      setStorageSync("agent_tableParams", _this.tableParams);

      apiAgentList(_this.tableParams)
        .then((response) => {
          const result = response;
          _this.tableData = result.data.datalist;
          _this.loading_end("table");
        })
        .catch(function (result) {
          _this.loading_end("table");
        });
    },

    // 初始化表单数据
    from_init() {
      this.form = { ...this.init_form };
    },
    // 表格操作
    handleTableEdit(index, row) {
      console.log(index, row);
      var form = this.form;
      form.id = row.id;
      form.group_id = row.group_id;
      form.mobile = row.mobile;
      form.nickname = row.nickname;
      form.account = row.username;
      this.handleDialogVisible(true, false);
      this.dialogConfig.title = "修改人员";
    },
    // 表格删除
    handleTableDelete(index, row) {
      const _this = this;
      this.$confirm("删除该人员?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          _this.loading_start("table");
          apiAgentDelete({ id: row.id })
            .then((response) => {
              if (response.code == 1) {
                _this.$message({
                  message: response.msg,
                  type: "success",
                });
                _this.req_list();
              } else {
                this.$message.error(response.msg);
                return false;
              }
              _this.loading_end("table");
            })
            .catch(() => {
              _this.loading_end("table");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消删除",
          });
        });
    },
    // 表格恢复
    handleTableRegain(index, row) {
      var _this = this;
      this.$confirm("是否恢复该人员?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var params = {
            id: row.id,
            status: "normal",
          };

          _this.loading_start("table");
          apiAgentUpdateSingle(params).then((response) => {
            _this.loading_end("table");
            _this.req_list();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消",
          });
        });
    },
    // 打开添加/修改输入框
    handleDialogVisible(status, is_init_from = true) {
      if (is_init_from) {
        this.from_init();
      }
      this.dialogFormVisible = status;
    },
    /**表单提交 */
    from_submit() {
      const _this = this;
      var param = { ...this.form };

      this.$refs["refForm"].validate((valid) => {
        if (valid) {
          if (
            param.password.length > 0 ||
            param.password_confirmation.length > 0
          ) {
            if (param.password != param.password_confirmation) {
              this.$message.error("二次输入密码不一致，请重新输入");
              return false;
            }
          }

          if (param.length > 0 && param.length < 6) {
            _this.$message.error("密码不能小于6位");
            return false;
          }

          if (param.length == 0) {
            delete param.password;
          }

          _this.loading_start("dialog_create");
          if (param.id == 0) {
            apiAgentCreate(param)
              .then((response) => {
                _this.loading_end("dialog_create");
                _this.handleDialogVisible(false);
                _this.$message({
                  message: response.msg,
                  type: "success",
                });
                _this.req_list();
              })
              .catch(function (result) {
                _this.loading_end("dialog_create");
              });
          } else {
            apiAgentUpdate(param)
              .then((response) => {
                _this.loading_end("dialog_create");
                _this.handleDialogVisible(false);
                _this.$message({
                  message: response.msg,
                  type: "success",
                });
                _this.req_list();
              })
              .catch(function (result) {
                _this.loading_end("dialog_create");
              });
          }
        }
      });
    },
    //获取职位
    req_group() {
      const _this = this;
      apiGroupList()
        .then((response) => {
          const result = response;
          this.group = result.data.list;
        })
        .catch(function (result) {
          _this.$message.error(result.msg);
        });
    },
    // 数量改变
    handleTableSizeChange(val) {
      this.tableParams.size = val;
      this.req_list();
    },
    // 页数改变
    handleTableCurrentChange(val) {
      this.tableParams.page = val;
      this.req_list();
      // console.log(`当前页: ${val}`);
    },
    // 加载开始...
    loading_start(keys) {
      if (Array.isArray(keys)) {
        keys.forEach((key) => {
          this.loading[key] = true;
          setTimeout(() => {
            this.loading[key] = false;
          }, 5000);
        });
      } else {
        this.loading[keys] = true;
        setTimeout(() => {
          this.loading[keys] = false;
        }, 5000);
      }
    },
    // 加载结束...
    loading_end(keys) {
      if (Array.isArray(keys)) {
        keys.forEach((key) => {
          this.loading[key] = false;
        });
      } else {
        this.loading[keys] = false;
      }
    },
  },
};
</script>

<style lang="scss"></style>
